;(function($){
	$.fn.spa_search_sel_jg = function(opts){
		var el = this;
		var opt = {
			bmh : "",
			ds : [],
			ds_all : [],
			type : "search",//search:查询模式;sel:选择模式;
			dataBack : function(){},
			closeBack : function(){},
		}
		var param = $.extend(opt,opts);
		var app = new App(el,param);
	}
	
	var App = function(el,param){
		this.el = el;
		this.param = param;
		var t = this;
		this.initHtml();
		this.initGrid();
		this.getJgDs("",function(data){
			t.setGridValue(data);
			t.initSelJgHtml(data);
		});
		this.bindEvent();
	}
	
	App.prototype = {
		bindEvent : function(){
			var el = this.el;
			var param = this.param;
			var t = this;
			
			//查找 /搜索切换
			el.find("#btnTypeChange").unbind("click").click(function(){
				el.find(".modal-body").toggle();
				if(param.type=="search"){
					param.type = "sel"
				}else if(param.type=="sel"){
					param.type = "search"
				}
			});
			
			//取消、关闭
			el.find("#btnModalCancel,#close-dialog").unbind("click").click(function(){
				el.modal("hide");
				el.empty();
				param.closeBack();
			})
			
			//确定按钮
			el.find("#btnModalCheck").unbind("#btnModalCheck").click(function(){
				if(param.type=="search"){
					grid_selector = el.find("#modalGridTable_pos_sel_fwy");
					var rowid = grid_selector.jqGrid('getGridParam','selrow');
					if(rowid){
						var rowdata = grid_selector.jqGrid('getRowData',rowid);
						param.dataBack(rowdata);
						el.modal("hide");
						el.empty();
					}else{
						jf_alert("请选择技工!!!")
					}
				}else if(param.type=="sel"){
					var selJgBtn = el.find("#alinusers_list").find(".alinuserBtn.btn-success");
					if(selJgBtn.size()>0){
						var json = $.parseJSON(selJgBtn.find(".json").text());
						param.dataBack(json);
						el.modal("hide");
						el.empty();
					}else{
						jf_alert("请选择技工!!!")
					}
				}
			});
			
			//搜索查询
			el.find("#modalBtnSearch").unbind("click").click(function(){
				t.searchJg();
			});
			
			//搜索回车事件
			el.find("#benefitForm").unbind("click").click(function(){
				el.find("#modalBtnSearch").trigger("click");
			});
			
			//选择查询
			el.find("#modalBtnSel").unbind("click").click(function(){
				t.selJgFilter();
			});
		},
		initHtml : function(){
			var el = this.el;
			var param = this.param;
			var t = this;
			
			//创建模态窗体
			this.el.addClass("modal").attr("tabindex","-1").attr("data-backdrop","static");
				
			html=	'<div class="modal-dialog" style="width:600px;" id="MarDebitModal">'+
						'<div class="modal-content">'+
							'<div class="modal-header no-padding">'+
								'<div class="table-header">'+
									'<button id="close-dialog" type="button" class="close" data-dismiss="modal" aria-hidden="true" value="HTML">'+
										'<span class="white">&times;</span>'+
									'</button>'+
									'<span id="modal-h4">'+
										$.i18n.propJsp("技工")+
									'</span>&nbsp;&nbsp;&nbsp;&nbsp;'+
								'</div>'+
							'</div>'+
							'<div id="selJg" class="modal-body" style="height:400px;display:none;">'+
								'<div id="places" class="col-sm-12 no-padding">'+
								
									'<div class="widget-box row" style="border:1px solid orange;">'+
										'<form id="jgSelForm" class="form-horizontal col-sm-10" onsubmit="return false;" style="margin-top:10px;">'+
											'<div class="col-sm-6 no-padding">'+
												'<div class="col-sm-4 no-padding">'+
													'<label class="col-sm-12 control-label no-padding-left" style="margin-bottom: 12px;">'+$.i18n.propJsp("编号")+'</label>'+
												'</div>'+
												'<div class="col-sm-8 no-padding">'+
													'<input id="bh" name="bh" class="input-md" type="text">'+
												'</div>'+
											'</div>'+
											
											'<div class="col-sm-6 no-padding">'+
												'<div class="col-sm-4 no-padding">'+
													'<label class="col-sm-12 control-label no-padding-left" style="margin-bottom: 12px;">'+$.i18n.propJsp("名称")+'</label>'+
												'</div>'+
												'<div class="col-sm-8 no-padding">'+
													'<input id="xm" name="xm" class="input-md" type="text">'+
												'</div>'+
											'</div>'+
										'</form>'+
										'<div class="col-sm-2" style="margin-top:10px;">'+
											'<div class="clearfix">'+
												'<div class="pull-left">'+
													'<div class="btn-group">'+
														'<button id="modalBtnSel" class="btn btn-sm btn-info">'+
															'<i class="ace-icon fa fa-search"></i>'+
															$.i18n.propJsp("查询")+
														'</button>'+
													'</div>'+
												'</div>'+
											'</div>'+
										'</div>'+
									'</div>'+
									
									'<div class="col-sm-12 no-padding" style="display:flex;">'+
										'<div id="alinusers_list" class="col-sm-12 no-padding" style="height:325px;overflow-y:auto;overflow-x:hidden;flex:1;">'+
										
										'</div>'+
										'<div id="lettersNavgation" style="width:50px;height:325px">'+
											
										'</div>'+
									'</div>'+
									
								'</div>'+
							'</div>'+
							'<div id="searchJg" class="modal-body" style="display:none;">'+
								'<div class="widget-box row" style="border:1px solid orange;">'+
									
									'<form id="benefitForm" class="form-horizontal col-sm-10" onsubmit="return false;" style="margin-top:10px;">'+
										
										'<div class="col-sm-2 no-padding">'+
											'<label style="margin-top:6px;">'+
												'<input class="ace" type="checkbox" name="sqlType" id="sqlType"/>'+
												'<span class="lbl">'+$.i18n.propJsp("编号模糊")+'</span>'+
											'</label>'+
										'</div>'+
								
										'<div class="col-sm-5 no-padding">'+
											'<div class="col-sm-4 no-padding">'+
												'<label class="col-sm-12 control-label no-padding-left" style="margin-bottom: 12px;">'+$.i18n.propJsp("编号")+'</label>'+
											'</div>'+
											'<div class="col-sm-8 no-padding">'+
												'<input id="uname" name="uname" class="input-md" type="text">'+
											'</div>'+
										'</div>'+
										
										'<div class="col-sm-5 no-padding">'+
											'<div class="col-sm-4 no-padding">'+
												'<label class="col-sm-12 control-label no-padding-left" style="margin-bottom: 12px;">'+$.i18n.propJsp("名称")+'</label>'+
											'</div>'+
											'<div class="col-sm-8 no-padding">'+
												'<input id="describ" name="describ" class="input-md" type="text">'+
											'</div>'+
										'</div>'+
									'</form>'+
									'<div class="col-sm-2" style="margin-top:10px;">'+
										'<div class="clearfix">'+
											'<div class="pull-left">'+
												'<div class="btn-group">'+
													'<button id="modalBtnSearch" class="btn btn-sm btn-info">'+
														'<i class="ace-icon fa fa-search"></i>'+
														$.i18n.propJsp("查询")+
													'</button>'+
												'</div>'+
											'</div>'+
										'</div>'+
									'</div>'+
								'</div>'+
								
								'<div class="widget-box">'+
									'<table id="modalGridTable_pos_sel_fwy"></table>'+
									'<div id="modalGridPage_pos_sel_fwy"></div>'+
								'</div>'+
							'</div>'+
							'<div class="modal-footer">'+
								'<div class="pull-left" width="50%">'+
									'<div class="btn-group">'+
										'<button id="btnTypeChange" class="btn btn-info btn-sm">'+
											$.i18n.propJsp('选择/搜索切换')+
										'</button>'+
									'</div>'+
								'</div>'+
							    '<div class="pull-right" width="50%">'+
									'<div class="btn-group">'+
										'<button id="btnModalCheck" class="btn btn-info btn-sm">'+
											'<i class="ace-icon fa fa-check"></i>'+
											$.i18n.propJsp('确认')+
										'</button>'+
									'</div>'+
									'<div class="btn-group">'+
										'<button id="btnModalCancel" class="btn btn-default btn-sm">'+
											'<i class="ace-icon fa fa-times"></i>'+
											$.i18n.propJsp('取消')+
										'</button>'+
									'</div>'+
								'</div>'+
							'</div>'+
						'</div>'+
					'</div>';
			el.html(html);
			el.find("#"+param.type+"Jg").show();
			el.modal("show");
		}, 
		initGrid : function(){
			
			var el = this.el;
			var param = this.param;
			var t = this;
			var grid_selector = this.el.find("#modalGridTable_pos_sel_fwy");
			var pager_selector = this.el.find("#modalGridPage_pos_sel_fwy");
			//构造表格
			grid_selector.jqGrid({
//				url : getContextPath() + "/pos/front/hoguest/proceduregrid",
				datatype : "local",
				width :566,
				height : 260,
				data : param.ds,
//				postData : $.HSAPI_ASKJSONINFO( JSON.stringify(initc),'RetrieveJqGrid'),
				colNames : ["编号","groupby","姓名","部门号","jg","pass","func","cp","depart","cp2","rights","cp_pre","cp_tc","cdepart"],
				colModel : [{
					name : "bh",//"bh",
					index : "bh",
					width : 140,
					key : true,
				},{
					name : "groupby",//"groupby",
					index : "groupby",
					width : 140,
					hidden : true,
				},{
					name : "xm",//"xm",
					index : "xm",
					width: 140,
				},{
					name : "bmh",//"bmh",
					index : "bmh",
					width : 140,
					hidden : true,
				},{
					name : "jg",//"jg",
					index : "jg",
					width: 140,
					hidden : true,
				},{
					name : "pass",//"pass",
					index : "pass",
					width : 140,
					hidden : true,
				},{
					name : "func",//"func",
					index : "func",
					width: 140,
					hidden : true,
				},{
					name : "cp",//"cp",
					index : "cp",
					width : 140,
					hidden : true,
				},{
					name : "depart",//"depart",
					index : "depart",
					width: 140,
					hidden : true,
				},{
					name : "cp2",//"cp2",
					index : "cp2",
					width : 140,
					hidden : true,
				},{
					name : "rights",//"rights",
					index : "rights",
					width: 140,
					hidden : true,
				},{
					name : "cp_pre",//"cp_pre",
					index : "cp_pre",
					width : 140,
					hidden : true,
				},{
					name : "cp_tc",//"cp_tc",
					index : "cp_tc",
					width: 140,
					hidden : true,
				},{
					name : "cdepart",//"cdepart",
					index : "cdepart",
					width: 140,
					hidden : true,
				}],    	
				sortname : "groupby",
				sortorder : "asc",
				viewrecords : true,
				rowNum : "全部",
				rowList:[10,20,30],
				emptyrecords: $.i18n.propJsp("没有搜索到任何数据"),
				recordtext: $.i18n.propJsp("共计")+":{2}"+$.i18n.propJsp("条"),
				pager : pager_selector,
				altRows : true,  
				scrollrows:true,
				shrinkToFit : true,
				multiselect : param.multi,//true
				scroll: true,
			    onSelectRow:function(rowid){
			    	rowdata = grid_selector.jqGrid("getRowData",rowid);
		        },
	        	ondblClickRow: function(rowid) { 
	        		el.find("#selectionModalSave_Sales").trigger("click");
	        	},
	        	loadComplete : function(data) {
	        		var table = this;
					setTimeout(function(){
						updatePagerIcons(table);
					}, 0);
				}, 
			});
		},
		getJgDs : function(whereString,back){
			var el = this.el;
			var param = this.param;
			var t = this;
			
			whereString = " and bmh = '"+param.bmh+"' " +whereString ;
			var arg1 = {"where":{"1":1},"fileds":["bh","groupby","xm","bmh","jg","pass","func","cp","depart","cp2","rights","cp_pre","cp_tc","cdepart"],
						"table":{"table":"viewJqGrid_ct_fwy"},"wherestring":["@@WS"," 1=1 "+whereString]}
			var arg2 = [{"page":1,"sord":"asc","rows":-1,"sidx":"groupby"}]
			jQuery.ajax({  
	    		type : 'POST',
	    		url : $.HSAPI_AJAXURL+"/qms/mobile/procedure2",
	    		data : $.HSAPI_ASKJSONINFO(JSON.stringify(arg1),'RetrieveJqGridList',JSON.stringify(arg2),"list"),// CRS_ResvCheckModify
	    		dataType : 'json',  
	    		success : function(data){
//	    			console.log(data);
	    			if(data.RETURN&&data.RETURN!=1){
	    				if(data.hasOwnProperty("gritter")){
							if(data.hasOwnProperty("gritterstyle"))
								jf_successDelayed(data.gritter,2000,data.gritterstyle);
							else
								jf_successDelayed(data.gritter,2000); 
						}
	    			}else{
    					param.ds = data;
	    				back(data);
					}
	    		},  
	    		error : function(data){
	    			jf_alert(JSON.stringify(data));
	    		}  
	    	});
		},
		setGridValue : function(ds){
			var el = this.el;
			var param = this.param;
			var t = this;
			var grid_selector = el.find("#modalGridTable_pos_sel_fwy");
			grid_selector.jqGrid("clearGridData");
			$(ds).each(function(k,v){
				grid_selector.jqGrid("addRowData",v.bh,v,"last");
			})
//			var balance  = grid_selector.getCol('balance',false,'sum'); 
//			var xfje  = grid_selector.getCol('xfje',false,'sum');
//			xfje = checkTwoPoint(xfje);
//			grid_selector.footerData("set",{"balance":balance,"xfje":xfje,"bz_c":$.i18n.propJsp("一起结账:")+xfje});
		},
		initSelJgHtml : function(ds){
			var el = this.el;
			var param = this.param;
			var t = this;
			var alinusersArr = []
			$(ds).each(function(key,value){
				var html =	'<div id="groupbyPlace_'+value.groupby+'" class="col-sm-12 no-padding" style="">'+
								'<div id="" class="col-sm-12 no-padding" style="background-color: #f4f4f4;height: 30px;line-height: 30px;">'+
									'<label style="margin-left: 10px;">'+
										'<span style="font-weight: bold;">'+value.groupby+'</span>'+
									'</label>'+
								'</div>'+
								'<div id="detailSpace_'+value.groupby+'" class="col-sm-12" style="padding-top: 10px;">'+
								'</div>'+
							'</div>';
				el.find("#alinusers_list").append(html)
				
				alinusersArr.push(value.groupby)
				
				var detailSpace_html = 	'<button data-filter="'+value.bh+value.xm+'" data-code="'+value.bh+'" data-groupby="'+value.groupby+'" class="btn btn-white btn-sm alinuserBtn" style="margin-right:10px;margin-bottom:10px;">'+
										'<span class="json hide">'+JSON.stringify(value)+'</span>'+
										value.xm+'-'+value.bh+	
									'</button>';
				el.find("#detailSpace_"+value.groupby).append(detailSpace_html)
			});
			if(!$.isFunction($().letters_navigation)){
				$.ajaxSetup({ async: false, cache: false });
	            $.getScript("js/cashier_mana/jquery.plugin.letters_navigation.js");
	            $.ajaxSetup({ async: true });
			}
			$("#lettersNavgation").letters_navigation({
				width:50,
				height:325,
				ds : ds,
				a_pre_id : "groupbyPlace_",
				nav_key : "groupby",
				dataBack : function(){
				}, 
			});
			t.bindJgEvent();
		},
		bindJgEvent : function(){
			var el = this.el;
			var param = this.param;
			var t = this;
			
			//地点单选
			el.find(".alinuserBtn").unbind("click").click(function(){
				var group = $(this).attr("data-groupby")
				//单选
				if($(this).hasClass("btn-success")){
					el.find(".alinuserBtn").removeClass("btn-success")
    				el.find(".alinuserBtn").addClass("btn-white")
    				$(this).removeClass("btn-success")
    				$(this).addClass("btn-white")
				}else{
					el.find(".alinuserBtn").removeClass("btn-success")
    				el.find(".alinuserBtn").addClass("btn-white")
    				$(this).addClass("btn-success")
    				$(this).removeClass("btn-white")
				}
			});
		},
		searchJg : function(){
			var el = this.el;
			var param = this.param;
			var t = this;
			var sqlType = el.find("#sqlType").is(":checked");
			var filter = "";
			var bh = el.find("#uname").val();
			var xm = el.find("#describ").val();
			var wherestring = '';
			if(sqlType){
				if(bh){
					wherestring += " and bh like '%"+bh+"%'";
				}
				if(xm){
					wherestring += "  and xm like '%"+xm+"%'";
				}
			}else{
				if(bh){
					wherestring += " and bh = '"+bh+"'";
				}
				if(xm){
					wherestring += " and xm = '"+xm+"'";
				}
			}
			
			t.getJgDs(wherestring,function(data){
				t.setGridValue(data);
			});	
		},
		selJgFilter : function(){
			var el = this.el;
			var param = this.param;
			var t = this;
			var bh = el.find("#bh").val();
			var xm = el.find("#xm").val();
			var alinuserBtn = null;
			if(bh){
				alinuserBtn = el.find(".alinuserBtn[data-filter*="+bh+"]");
			}
			if(xm){
				alinuserBtn = el.find(".alinuserBtn[data-filter*="+xm+"]");
			}
			if(alinuserBtn&&alinuserBtn.size()>0){
				el.find(".alinuserBtn").addClass("btn-white").removeClass("btn-success");
				alinuserBtn.eq(0).addClass("btn-success").removeClass("btn-white");
				el.find("#alinusers_list").animate({scrollTop:alinuserBtn.eq(0).offset().top-89},0)
			}
		},
	}
	
	/*
	 * 私有函数
	 * 翻页栏
	 * 
	 */
	function updatePagerIcons(table){
		var replacement = {
				"ui-icon-seek-first" : "ace-icon fa fa-angle-double-left bigger-140",
				"ui-icon-seek-prev" : "ace-icon fa fa-angle-left bigger-140",
				"ui-icon-seek-next" : "ace-icon fa fa-angle-right bigger-140",
				"ui-icon-seek-end" : "ace-icon fa fa-angle-double-right bigger-140"
		};
		$(".ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon").each(function() {
			var icon = $(this);
			var $class = $.trim(icon.attr("class").replace("ui-icon", ""));

			if ($class in replacement)
				icon.attr("class", "ui-icon " + replacement[$class]);
		});
	};
	
})(jQuery);